package com.terry.sp.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.terry.sp.core.Result;
import com.terry.sp.core.ResultGenerator;
import com.terry.sp.core.exception.ServiceException;
import com.terry.sp.model.Device;
import com.terry.sp.model.PrintTask;
import com.terry.sp.service.DeviceService;
import com.terry.sp.service.PrintTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * Created by CodeGenerator on 2019/04/21.
 */
@RestController
@Slf4j
@RequestMapping("/ptask")
public class PrintTaskController {

    @Value("${TempFilePath}")
    private String TempFilePath;

    @Resource
    private PrintTaskService printTaskService;

    @Resource
    private DeviceService deviceService;

    @PostMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        printTaskService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(PrintTask printTask) {
        printTaskService.update(printTask);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        PrintTask printTask = printTaskService.findById(id);
        return ResultGenerator.genSuccessResult(printTask);
    }

    @PostMapping("/list")
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<PrintTask> list = printTaskService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/getTask")
    public Result getTask(@RequestParam Integer deviceId) {
        if (deviceId > 0) {
            PrintTask task = printTaskService.getTaskByDeviceId(deviceId);
            if (task != null) {
                return ResultGenerator.genSuccessResult(task);
            }
            return ResultGenerator.genFailResult("没有任务");
        } else {
            throw new ServiceException("请传入设备号!");
        }
    }

    @PostMapping(value = "/finish")
    public Result finishTask(@RequestParam Integer taskId) {
        printTaskService.finishTaskById(taskId);
        return ResultGenerator.genSuccessResult(taskId);
    }

    @PostMapping(value = "/add")
    public Result uploadFileBufferToLocal(HttpServletRequest request, @RequestParam("file") MultipartFile file) {

        String fileSender = request.getParameter("fileSender");
        String deviceId_str = request.getParameter("deviceId");
        String copies_str = request.getParameter("copies");

        log.info(String.format("formData(FileSender, DeviceId, Copies):[%s] [%s] [%s]", fileSender, deviceId_str, copies_str));

        int deviceId = Integer.parseInt(deviceId_str);
        int copies = Integer.parseInt(copies_str);

        Device device = deviceService.findById(deviceId);

        if (device == null) throw new ServiceException(String.format("未找到对应的设备! 设备Id:%d", deviceId));

        log.info(String.format("收到从%s上传的文件.", device.getLocation()));

        PrintTask task = new PrintTask();
        task.setCopies(copies);
        task.setCreateTime(new Date());
        task.setFilename(file.getOriginalFilename());
        task.setDeviceId(deviceId);
        task.setFileSender(fileSender);
        task.setFileType(1);
        task.setState(PrintTask.TASK_STATE_INIT);
        task.setPrinterName("default printer");

        printTaskService.addTask(file, task);

        return ResultGenerator.genSuccessResult(task.getId());

    }

    @PostMapping(value = "/print")
    @ResponseBody
    public Result print(@RequestBody int[] tasks) {
        printTaskService.printTasks(tasks);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        int taskId = Integer.parseInt(request.getParameter("taskId"));
        if (taskId <= 0) throw new ServiceException("请传入设备号!");
        PrintTask task = printTaskService.getTaskById(taskId);
        if (task != null) {
            String fileName = TempFilePath + "/" + task.getFilename();
            File file = new File(fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                log.error("要下载的文件不存在:" + fileName);
                throw new ServiceException("要下载的文件不存在:" + fileName);
            }
        }
//        return ResultGenerator.genFailResult("没有任何任务");
    }

    @PostMapping("/setComplete")
    public Result setTaskCompleted(@RequestParam Integer taskId) {
        PrintTask task = printTaskService.findById(taskId);
        task.setState(PrintTask.TASK_STATE_DONE);
        printTaskService.update(task);
        return ResultGenerator.genSuccessResult();
    }


}
